'''
Knowtemarks
===========
A simple tool to manage your notes and bookmarks

@author: Markus Fuchs, 2012
'''

import json, logging
from knowtemarks.DataModel import Knowte
from tornado.web import RequestHandler

log = logging.getLogger("main.ajaxHandler")

class BaseJsonHandler(RequestHandler):
    """
    A basic AJAX request handler which one should inherit from.
    It expects doGet() and doPost() methods to be implemented and
    they should return a dictionary which is returned to the client
    as a json object.
    It is also possible to set the return Status via the self.status
    variable.
    """
    def __init__(self, application, request, knowteDao, **kwargs):
        RequestHandler.__init__(self, application, request, **kwargs)
        self.knowteDao = knowteDao
        self.status = 200
    def get(self, *args, **kwargs):
        js = self.doGet(*args, **kwargs)
        self.set_header("Content-Type", "application/json")
        self.set_status(self.status)
        self.write(json.dumps(js))
    
    def doGet(self, *args, **kwargs):
        pass
    
    def post(self, *args, **kwargs):
        js = self.doPost(*args, **kwargs)
        self.set_header("Content-Type", "application/json")
        self.set_status(self.status)
        self.write(json.dumps(js))
    
    def doPost(self, *args, **kwargs):
        pass

##############################################################
# 
# The following handlers actually do something ;)
#
class AjaxHandler(BaseJsonHandler):
    """
    Handles Ajax Requests and returns json objects
    which include possible error messages
    """
    def doPost(self, *args, **kwargs):
        log.debug("got args %s with arguments %s", args, self.request.arguments)
        a = list(args)
        res = {"errors":[]}
        if a[0] == "edit":
            try:
                i = int(a[2])
            except:
                res["errors"].append("URL format failure")
                self.status = 400
                return res
            k = Knowte()
            k.id = i
            k.title = self.get_argument("title")
            k.url = self.get_argument("url", "")
            k.info = self.get_argument("info", "")
            k.setTags([ s for s in self.get_argument("tagString").split(" ")])
            return self.editKnowte(k, res)
        elif a[0] == "delete":
            try:
                i = int(a[2])
            except:
                res["errors"].append("URL format failure")
                self.status = 400
                return res
            return self.deleteKnowte(i, res)
        elif a[0] == "add":
            k = Knowte()
            k.title = self.get_argument("title")
            k.url = self.get_argument("url", "")
            k.info = self.get_argument("info", "")
            k.setTags([ s for s in self.get_argument("tagString").split(" ")])
            return self.addKnowte(k, res)
        else:
            res["errors"].append("Unknown command")
            self.status = 400
            
        return res
    
    def addKnowte(self, k, jso):
        self.knowteDao.storeKnowte(k)
        return jso
    
    def editKnowte(self, k, jso):
        if jso is None: jso = dict()
        self.knowteDao.editKnowte(k.id, k)
        return jso
    
    def deleteKnowte(self, i, jso):
        if jso is None: 
            jso = dict()
            jso["errors"] = []
        try: 
            self.knowteDao.deleteKnowte(i)
        except:
            jso.errors.append("Unknown Error")
        return jso